package com.cloud.little.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cloud.little.config.exception.handler.BusinessException;
import com.cloud.little.config.util.AssertUtil;
import com.cloud.little.config.util.Json;
import com.cloud.little.entity.Goods;
import com.cloud.little.service.IGoodsService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 商品管理员维护
 * </p>
 *
 * @author author
 * @since 2020-08-16
 */
@RestController
@RequestMapping("/admin/goods")
public class AdminGoodsController {
    @Resource
    private IGoodsService goodsService;


    /**
     * 商品分页
     */
    @PostMapping("/getGoodsPage")
    public JSONObject getGoodsPage(Page<Goods> page, Goods goods) {
//        PageToWrapper<Goods> goodsPageToWrapper = new PageToWrapper<>();
//        Wrapper<Goods> wrapper = goodsPageToWrapper.getWrapper(goods);
        EntityWrapper<Goods> goodsEntityWrapper = new EntityWrapper<>();
        if(!StringUtils.isEmpty(goods.getGoodsName())) {
            goodsEntityWrapper.like("goodsName", goods.getGoodsName());
        }
        goodsEntityWrapper.orderBy("createTime", false);
        return Json.success(goodsService.selectPage(page, goodsEntityWrapper));
    }

    /**
     * 根据商品主键id查看商品详情
     */
    @PostMapping("/getGoodsByGoodsId")
    public JSONObject getGoodsByGoodsId(Goods goods) {
        AssertUtil.isNotNull(goods.getId(), "请输入商品id");
        return Json.success(goodsService.selectById(goods.getId()));
    }

    /**
     * 插入或者更新商品详情，有传入主键则为更新
     */
    @PostMapping("/addOrUpdateGoods")
    public JSONObject addOrUpdateGoods(Goods goods)  {
        AssertUtil.isNotNull(goods.getGoodsName(), "请输入商品名称");
        AssertUtil.isNotNull(goods.getInventory(), "请输入商品库存");
        AssertUtil.isNotNull(goods.getPrice(), "请输入商品价格");
        if (goods.getInventory() < 0) {
            throw new BusinessException("库存数量必须大于0");
        }
        if (goods.getPrice().compareTo(new BigDecimal(0)) <= 0) {
            throw new BusinessException("价格必须大于0");
        }
        return goodsService.addOrUpdateGoods(goods);
    }

    /**
     * 删除
     */
    @PostMapping("/deleteGoods")
    public JSONObject deleteGoods(Goods goods)  {
        AssertUtil.isNotNull(goods.getId(),"请传入id");
         goodsService.deleteById(goods.getId());
        return Json.success();
    }


}

